package com.training.controller;

import com.training.entity.*;
import com.training.service.ClassService;
import com.training.service.QaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/qa")
public class QaController {

    @Autowired
    private QaService qaService;

    @Autowired
    private ClassService classService; // 假设您有ClassService用于获取班级列表

    // 问答广场，显示所有问题
    @GetMapping("/browse")
    public String browseQuestions(@RequestParam(name = "keyword", required = false) String keyword, Model model) {
        List<TopicQuestion> questions = qaService.getQuestions(keyword);
        model.addAttribute("questions", questions);
        model.addAttribute("keyword", keyword);
        return "qa-browse";
    }

    // 显示提问页面
    @GetMapping("/ask")
    public String showAskForm(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        model.addAttribute("question", new TopicQuestion());
        model.addAttribute("categories", qaService.getAllCategories());

        // --- 核心修复点 ---
        // 调用 getAllClasses 方法时传入 null，以获取所有班级
        model.addAttribute("classes", classService.getAllClasses(null));

        return "qa-ask";
    }

    // 处理提问表单提交
    @PostMapping("/ask")
    public String askQuestion(@ModelAttribute("question") TopicQuestion question, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }
        question.setUserId(user.getId());

        try {
            qaService.createQuestion(question);
            redirectAttributes.addFlashAttribute("successMessage", "问题发布成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "发布失败：" + e.getMessage());
            return "redirect:/qa/ask";
        }

        return "redirect:/qa/browse";
    }

    // 查看问题详情和回答
    @GetMapping("/detail/{id}")
    public String questionDetail(@PathVariable("id") Long id, Model model) {
        TopicQuestion question = qaService.getQuestionDetail(id);
        if (question == null) {
            return "redirect:/qa/browse";
        }
        List<TopicQuestionComment> comments = qaService.getCommentsByQuestionId(id);

        model.addAttribute("question", question);
        model.addAttribute("comments", comments);
        model.addAttribute("newComment", new TopicQuestionComment());
        return "qa-detail";
    }

    // 回答问题
    @PostMapping("/detail/{id}/reply")
    public String replyQuestion(@PathVariable("id") Long id, @ModelAttribute("newComment") TopicQuestionComment comment, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        comment.setQId(id);
        comment.setUserId(user.getId());

        try {
            qaService.createComment(comment);
            redirectAttributes.addFlashAttribute("successMessage", "回答成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "回答失败：" + e.getMessage());
        }

        return "redirect:/qa/detail/" + id;
    }

    // 采纳回答
    @PostMapping("/comment/{commentId}/adopt")
    public String adoptComment(@PathVariable("commentId") Long commentId, @RequestParam("questionId") Long questionId, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        try {
            qaService.adoptComment(questionId, commentId, user.getId());
            redirectAttributes.addFlashAttribute("successMessage", "采纳成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败：" + e.getMessage());
        }

        return "redirect:/qa/detail/" + questionId;
    }
}